import { DbService } from './../fraction/services/db.service';
import * as fs from 'fs';
import * as XLSX from 'xlsx';
import { Injectable } from '@nestjs/common';

@Injectable()
export class XlsxService {
    constructor(
        public dbService: DbService,
    ) {

    }
    ObjArr = [];
    payRoll = [];
    XlsToJson(path: string, isfraction: boolean): any {
        let files = [];
        if (fs.existsSync(path)) {
            files = fs.readdirSync(path);
            files.forEach((file, index) => {
                const curPath = path + '/' + file;
                if (fs.statSync(curPath).isDirectory()) { // recurse
                    this.XlsToJson(curPath, isfraction);
                } else {
                    const info = file.split('.');
                    if (file && info[1] && (info[1] === 'xls' || info[1] === 'xlsx')) {
                        const workbook = XLSX.readFile(curPath);
                        const sheetNames = workbook.SheetNames;
                        const worksheet = workbook.Sheets[sheetNames[0]];
                        if (isfraction) {
                             this.fraction(worksheet);
                        } else {
                             this.payroll(worksheet);
                        }
                    }
                }
            });
        }
    }

    gotPayroll(path){
        this.payRoll = [];
        this.XlsToJson(path,false);
        return this.payRoll;
    }
    payroll(worksheet) {
        this.payRoll = [];
        let jsonArr = XLSX.utils.sheet_to_json(worksheet, {
            header: 1,
            defval: '',
        });
        this.payRoll = JSON.parse(JSON.stringify(jsonArr).replace(/,\["",("",?)+\]/g, ""));
    }

    GotObjArr(path: string, dept: string): Array<object> {
        this.ObjArr = [];
        this.XlsToJson(path, true);
        const date = `${(new Date()).getFullYear()}-${(new Date()).getMonth()}`;
        this.dbService.create({
            dept,
            userInfo: this.ObjArr,
            date,
        });
        return this.ObjArr;
    }
    fraction(worksheet) {
        const obj: any = {};
        obj.name = (worksheet.B2 && worksheet.B2.v) || '没名字';
        obj.department = (worksheet.D2 && worksheet.D2.v) || '没部门';
        obj.time = (worksheet.I2 && worksheet.I2.v) || '没写时间';
        obj.charge = (worksheet.G2 && worksheet.G2.v) || '没写负责人';
        obj.totalArray = [];
        obj.total = 0;
        let keys = Object.keys(worksheet);
        keys = keys.filter(key => key[0] !== '!');
        keys.forEach((key, i) => {
            if (worksheet[key].v.toString() === '合计') {
                worksheet[keys[i + 1]] && worksheet[keys[i + 1]].v && obj.totalArray.push(parseInt(worksheet[keys[i + 1]].v, 10) || 0);
                obj.total = obj.total + parseInt(worksheet[keys[i + 1]].v, 10);
            }
        });
        this.ObjArr.push(obj);
    }


}